home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / CTOOLS10.ARJ / HASHPJW.C < prev    next >
C/C++ Source or Header  |  1991-12-31  |  2KB  |  67 lines

  1. /****************************************************************************
  2. *
  3. *                    Copyright (C) 1991 Kendall Bennett.
  4. *                            All rights reserved.
  5. *
  6. * Filename:        $RCSfile: hashpjw.c $
  7. * Version:        $Revision: 1.3 $
  8. *
  9. * Language:        ANSI C
  10. * Environment:    any
  11. *
  12. * Description:    Hash function for strings. Provides better hashing than does
  13. *                hash_add().
  14. *
  15. * $Id: hashpjw.c 1.3 91/12/31 19:40:11 kjb Exp $
  16. *
  17. * Revision History:
  18. * -----------------
  19. *
  20. * $Log:    hashpjw.c $
  21. * Revision 1.3  91/12/31  19:40:11  kjb
  22. * Modified include file directories.
  23. * Revision 1.2  91/09/01  16:48:39  ROOT_DOS
  24. * Changed inlclude file search to search current directory
  25. * Revision 1.1  91/08/16  13:15:21  ROOT_DOS
  26. * Initial revision
  27. ****************************************************************************/
  28.  
  29. #include "debug.h"
  30. #include "hash.h"
  31.  
  32. #define    NBITS_IN_UNSIGNED        ( NBITS(unsigned int) )
  33. #define SEVENTY_FIVE_PERCENT    ((int)(NBITS_IN_UNSIGNED * .75))
  34. #define    TWELVE_PERCENT            ((int)(NBITS_IN_UNSIGNED * .125))
  35. #define    HIGH_BITS                ( ~( (unsigned)(~0) >> TWELVE_PERCENT) )
  36.  
  37. PUBLIC unsigned hash_pjw(unsigned char *name)
  38. /****************************************************************************
  39. *
  40. * Function:        hash_pjw
  41. * Parameters:    name    - String to hash
  42. * Returns:        hash value for the string
  43. *
  44. * Description:    This hash function uses a shift-and-XOR strategy to
  45. *                randomise the input key. The main iteration of the loop
  46. *                shifts the accumulated hash value to the left by a few
  47. *                bits and adds in the current character. When the number
  48. *                gets too large, it is randomised by XORing it with a
  49. *                shifted version of itself.
  50. *
  51. ****************************************************************************/
  52. {
  53.     unsigned    h = 0;            /* The hash value */
  54.     unsigned    g;
  55.  
  56.     for (; *name; name++) {
  57.         h = (h << TWELVE_PERCENT) + *name;
  58.         if ( (g = h & HIGH_BITS) != 0)
  59.             h = (h ^ (g >> SEVENTY_FIVE_PERCENT)) & ~HIGH_BITS;
  60.         }
  61.  
  62.     return h;
  63. }
  64.